import './ProjectManagement.scss';
import { useState, useMemo } from 'react';
import {
  Breadcrumb,
  Button,
  Form,
  Input,
  Table,
  Drawer,
  Tree,
  Modal,
  Select,
} from 'antd';
import {
  SearchOutlined,
  DoubleRightOutlined,
  EditOutlined,
  PlusCircleOutlined,
  MinusCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { DataNode } from 'antd/es/tree';

const { Search } = Input;
const x = 3;
const y = 2;
const z = 1;
const defaultData: DataNode[] = [];

const generateData = (
  _level: number,
  _preKey?: React.Key,
  _tns?: DataNode[]
) => {
  const preKey = _preKey || '0';
  const tns = _tns || defaultData;

  const children: React.Key[] = [];
  for (let i = 0; i < x; i++) {
    const key = `${preKey}-${i}`;
    tns.push({ title: key, key });
    if (i < y) {
      children.push(key);
    }
  }
  if (_level < 0) {
    return tns;
  }
  const level = _level - 1;
  children.forEach((key, index) => {
    tns[index].children = [];
    return generateData(level, key, tns[index].children);
  });
};
generateData(z);

const dataList: { key: React.Key; title: string }[] = [];
const generateList = (data: DataNode[]) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const { key } = node;
    dataList.push({ key, title: key as string });
    if (node.children) {
      generateList(node.children);
    }
  }
};
generateList(defaultData);

const getParentKey = (key: React.Key, tree: DataNode[]): React.Key => {
  let parentKey: React.Key;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey!;
};

/* table */
interface DataType {
  key: React.Key;
  id: number;
  name: string;
  tel: string;
  idCard: string;
  grade: string;
  class: string;
  time: string;
  status: number;
}

const columns: ColumnsType<DataType> = [
  {
    title: '项目编号',
    dataIndex: 'id',
  },
  {
    title: '项目名称',
    dataIndex: 'name',
  },
  {
    title: '缴费金额',
    dataIndex: 'tel',
  },
  {
    title: '机构层级二',
    dataIndex: 'idCard',
  },
  {
    title: '机构层级三',
    dataIndex: 'grade',
  },
  {
    title: '开始日期',
    dataIndex: 'class',
  },
  {
    title: '结束日期',
    dataIndex: 'time',
  },
  {
    title: '状态',
    dataIndex: 'status',
  },
];

const data: DataType[] = [
  {
    key: 1,
    id: 1,
    name: '伙食费',
    tel: '500',
    idCard: '年级',
    grade: '班级',
    class: '2021-02-02',
    time: '2021-02-08',
    status: 1,
  },
  {
    key: 2,
    id: 2,
    name: '班费',
    tel: '500',
    idCard: '年级',
    grade: '班级',
    class: '2021-02-02',
    time: '2021-02-08',
    status: 1,
  },
  {
    key: 3,
    id: 3,
    name: '校服费',
    tel: '500',
    idCard: '年级',
    grade: '班级',
    class: '2021-02-02',
    time: '2021-02-08',
    status: 1,
  },
];

// rowSelection object indicates the need for row selection
const rowSelection = {
  onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      'selectedRows: ',
      selectedRows
    );
  },
};
const StudentManagement: React.FC = () => {
  const [open, setOpen] = useState<boolean>(false);
  const [addOpen, setAddOpen] = useState<boolean>(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    const newExpandedKeys = dataList
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, defaultData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(newExpandedKeys as React.Key[]);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  const treeData = useMemo(() => {
    const loop = (data: DataNode[]): DataNode[] =>
      data.map((item) => {
        const strTitle = item.title as string;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className="site-tree-search-value">{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{strTitle}</span>
          );
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) };
        }

        return {
          title,
          key: item.key,
        };
      });

    return loop(defaultData);
  }, [searchValue]);

  /* var and func */
  const [form] = Form.useForm();
  //add
  const onAdd = () => {
    setAddOpen(true);
  };
  //edit
  const onEdit = () => {
    setAddOpen(true);
  };
  //delete
  const onDel = () => {
    setIsModalOpen(true);
  };
  //search
  const onSearch = () => {};
  //reset
  const onReset = () => {};
  //advanced search
  const showDrawer = () => {
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
  };
  const onFinish = () => {};
  //upload
  const onUpload = () => {};
  return (
    <div className="container">
      <div className="student">
        <Breadcrumb separator=">">
          <Breadcrumb.Item>
            <Button type="link" style={{ color: '#333' }}>
              缴费管理
            </Button>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <Button type="link" style={{ color: '#333' }}>
              缴费项目管理
            </Button>
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="content-box">
          <div className="left-box">
            <div className="left-title">
              <div style={{ marginLeft: '20px', width: 150 }}>组织机构</div>
              <div>
                <EditOutlined style={{ marginRight: '20px' }} />
                <PlusCircleOutlined style={{ marginRight: '20px' }} />
                <MinusCircleOutlined style={{ marginRight: '20px' }} />
              </div>
            </div>
            <div className="left-content">
              <Search
                style={{ marginBottom: 30, marginTop: 32, width: 200 }}
                placeholder="请搜索"
                onChange={onChange}
              />
              <Tree
                style={{ width: 200 }}
                showLine={true}
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                treeData={treeData}
              />
            </div>
          </div>
          <div className="right-box">
            <div className="header-box">
              <div className="operation-box">
                <Button
                  type="primary"
                  style={{ background: '#69657e' }}
                  onClick={onAdd}
                >
                  新增
                </Button>
                <Button
                  type="primary"
                  style={{ background: '#69657e' }}
                  onClick={onEdit}
                >
                  修改
                </Button>
                <Button
                  type="primary"
                  style={{ background: '#69657e' }}
                  onClick={onDel}
                >
                  删除
                </Button>
                <Button
                  type="primary"
                  style={{ background: '#69657e' }}
                  onClick={onUpload}
                >
                  审核
                </Button>
              </div>
              <div className="search-box">
                <Form form={form} name="control-hooks" layout="inline">
                  <Form.Item name="search">
                    <Input placeholder="请输入关键字搜索" />
                  </Form.Item>

                  <Form.Item>
                    <Button
                      type="primary"
                      style={{ background: '#69657e' }}
                      htmlType="submit"
                      onClick={onSearch}
                    >
                      <SearchOutlined />
                    </Button>
                    <Button
                      type="primary"
                      style={{ background: '#69657e' }}
                      onClick={onReset}
                    >
                      重置
                    </Button>
                  </Form.Item>
                </Form>
                <Button type="link" onClick={showDrawer}>
                  高级筛选
                  <DoubleRightOutlined
                    rotate={90}
                    style={{ color: '#d4d2d2' }}
                  />
                </Button>
              </div>
            </div>

            <Table
              bordered={true}
              rowSelection={{
                type: 'radio',
                ...rowSelection,
              }}
              columns={columns}
              dataSource={data}
              pagination={{
                defaultPageSize: 5,
                defaultCurrent: 1,
                total: 100,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: [5, 10, 15, 20],
                position: ['bottomLeft'],
              }}
            />
            <div className="drawer">
              <Drawer
                title="高级筛选"
                style={{
                  marginLeft: '750px',
                  marginTop: '200px',
                  width: '58%',
                }}
                placement="top"
                height={200}
                closable={true}
                onClose={onClose}
                open={open}
                getContainer={() => document.querySelector('.header-box')!}
              >
                <Form
                  layout="inline"
                  name="highSearch"
                  initialValues={{ remember: true }}
                  onFinish={onFinish}
                  autoComplete="off"
                >
                  <Form.Item label="姓名" name="name">
                    <Input placeholder="请输入姓名" />
                  </Form.Item>

                  <Form.Item label="身份证号" name="idCard">
                    <Input placeholder="请输入身份证号" />
                  </Form.Item>

                  <Form.Item>
                    <Button
                      type="primary"
                      style={{ background: '#69657e' }}
                      htmlType="submit"
                    >
                      查询
                    </Button>
                  </Form.Item>
                  <Form.Item>
                    <Button
                      type="primary"
                      style={{ background: '#69657e' }}
                      onClick={onReset}
                    >
                      重置
                    </Button>
                  </Form.Item>
                </Form>
              </Drawer>
            </div>
          </div>
        </div>
      </div>
      {/* 新增 */}
      <Modal
        title="缴费项目-新增"
        centered
        open={addOpen}
        onOk={() => setAddOpen(false)}
        onCancel={() => setAddOpen(false)}
        width={1280}
      >
        <Form
          name="addData"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
          initialValues={{ status: '0', grade: '0', class: '0' }}
          autoComplete="off"
        >
          <Form.Item label="项目编号" name="id">
            <Input placeholder="请输入项目编号" />
          </Form.Item>
          <Form.Item label="项目名称" name="name">
            <Input placeholder="请输入项目名称" />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select
              options={[
                {
                  value: '0',
                  label: '审核',
                },
                {
                  value: '1',
                  label: '发布',
                },
              ]}
            />
          </Form.Item>

          <Form.Item label="缴费金额" name="tel">
            <Input placeholder="请输入缴费金额" />
          </Form.Item>
          <Form.Item label="年级" name="idCard">
            <Select
              options={[
                {
                  value: '0',
                  label: '一年级',
                },
                {
                  value: '1',
                  label: '二年级',
                },
                {
                  value: '2',
                  label: '三年级',
                },
              ]}
            />
          </Form.Item>
          <Form.Item label="班级" name="grade">
            <Select
              options={[
                {
                  value: '0',
                  label: '3班',
                },
                {
                  value: '1',
                  label: '4班',
                },
              ]}
            />
          </Form.Item>
          <Form.Item label="开始日期" name="class">
            <Input placeholder="请输入开始日期" />
          </Form.Item>
          <Form.Item label="结束日期" name="time">
            <Input placeholder="请输入结束日期" />
          </Form.Item>
        </Form>
      </Modal>
      {/* 删除 */}
      <Modal
        title="提示"
        open={isModalOpen}
        onOk={() => {
          setIsModalOpen(false);
        }}
        onCancel={() => {
          setIsModalOpen(false);
        }}
      >
        <p>确定要删除选中学生吗？</p>
      </Modal>
    </div>
  );
};

export default StudentManagement;
